<?php

namespace App\Jobs;

use App\Models\LandownersOrder;
use App\Services\ComissionService;
use App\Services\CommissionService;
use App\Services\LandownersOrderService;
use App\Services\UserAccountService;
use Illuminate\Support\Facades\DB;

class LandownersOrderConfirmJob extends Job
{
    protected $job_name ='LandownersOrderConfirmJob';
    private $runtime = null;
    private $rows_per_loop =10;

    /**
     * 创建一个新的任务实例。
     *
     * @param $time 启动时间
     */
    public function __construct($time)
    {
        parent::__construct();
        $this->runtime = $time;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        //业务说明：商品订单定时确认收货

        $this->logger->info('========start======');
        $this->logger->info('runtime:'.$this->runtime);

        $time = DB::table('config')->where('code','order_info_confirm')->value('value');//自动收货时间 （天）
        //商品订单
        $timeline = $this->runtime;
        $this->confirmLandownersOrder($time,$timeline);

        $this->logger->info('========end======');
    }

    private function confirmLandownersOrder($time=7,$timeline){

        $commission = new CommissionService();
        $user_account = new UserAccountService();
        $this->logger->info('========商品订单======');

        $i =1;//批次
        $orders =null;

        while(true){

            $this->logger->info('【第'.$i.'批】');
            /* 默认7天 */
            $confirm_time = $time*24*3600;
            /* 已发货的订单 */
            $orders_info = LandownersOrder::where('ship_time','<',$timeline - $confirm_time )
                ->where('status','=',LANDOWNERS_ORDRE_SHIPPED)
                ->skip(0)->take($this->rows_per_loop)
                ->get();
            $orders = array_pluck($orders_info,'order_id');
            $this->logger->info('总数:'.count($orders));

            if(count($orders)==0){
                break;
            }

            $this->logger->info('执行: '.json_encode($orders));

            DB::beginTransaction();

            try{

                /* 更新订单状态 */
                DB::table('landowners_order')
                    ->whereIn('order_id',$orders)
                    ->update([
                        'status' => LANDOWNERS_ORDRE_FINISHED,//已完成
                        'finished_time' => $timeline
                    ]);

                /* 操作记录 */
                foreach ($orders_info as $order_id )
                {
                    //更新对应发货单状态
                    DB::table('landowners_deliver')
                        ->where('deliver_id',$order_id->deliver_id)
                        ->update([
                            'status' =>1, //单次收货完成
                            'take_time' => $timeline
                        ]);

                    //更新订单操作日志
                    $landowners_order_log = new LandownersOrderService();
                    $landowners_order_log->addLandownersOrderLog($order_id->order_id,'系统',LANDOWNERS_ORDRE_SHIPPED,LANDOWNERS_ORDRE_FINISHED,'超过自动收货时间自动确认收货',$order_id->deliver_id,'');

                    //判断订单是否全部发货 获取已发货并完成的次数
                    $count_deliver = DB::table('landowners_deliver')
                                            ->where('order_id',$order_id->order_id)
                                            ->where('status',1)
                                            ->count();
                    //如果发货次数不足修改订单状态进行下次发货
                    if($count_deliver < $order_id->deliver_count){
                        /* 更新订单状态 */
                        DB::table('landowners_order')
                            ->where('order_id',$order_id->order_id)
                            ->update([
                                'status' => LANDOWNERS_ORDER_ACCEPTED,
                                'finished_time' => $timeline
                            ]);
                        //更新订单操作日志
                        $landowners_order_log->addLandownersOrderLog($order_id->order_id,'系统',LANDOWNERS_ORDRE_FINISHED,LANDOWNERS_ORDER_ACCEPTED,'完成单次流程,进入下次流程','','');
                    }elseif($count_deliver == $order_id->deliver_count){ //货已发完计算收益

                        //用户确认收货收益计算
                        $account_money = $commission->getCommission($order_id->seller_id,$order_id->order_amount,'landowners');

                        //平台收益
                        $admin_commission = $account_money['franchisee_commission_goods']; //平台收益比例
                        $admin_money = 	$account_money['admin_money'];

                        //加盟商收益
                        $franchisee_commission = $account_money['partner_commission']; //加盟商收益比例
                        $franchisee_money = $account_money['franchisee_money'];

                        //合伙人收益
                        $partner_money = $account_money['partner_money'];

                        //账户资金操作  以及记录日志
                        if($admin_money > 0 ){
                            $user_account->incomeMoney(1,$admin_money,'结算做地主订单:订单编号:'.$order_id->order_sn.'分成比例:'.$admin_commission.'%',$order_id->order_id,'landowners','+');
                        }

                        if($franchisee_money > 0 && $account_money['franchisee_id'] > 0){
                            $user_account->incomeMoney($account_money['franchisee_id'],$franchisee_money,'结算做地主订单:订单编号:'.$order_id->order_sn.'分成比例:'.$franchisee_commission.'%',$order_id->order_id,'landowners','+');
                        }

                        if($partner_money > 0){
                            $user_account->incomeMoney($order_id->seller_id,$partner_money,'结算做地主订单:订单编号:'.$order_id->order_sn.'',$order_id->order_id,'landowners','+');
                        }
                        //获取购买数量更新销量
                        $count_deliver = DB::table('landowners_deliver')
                            ->where('order_id',$order_id->order_id)
                            ->where('status',1)
                            ->count();
                        //订单完成更新销量
                        DB::table('landowners_statistics')
                            ->leftjoin('landowners_deliver','landowners_deliver.landowners_id','=','landowners_statistics.landowners_id')
                            ->where('landowners_deliver.order_id',$order_id->order_id)
                            ->increment('sales',$count_deliver);
                    }
                }
                DB::commit();

            } catch(\Exception $e){
                DB::rollback();
                $this->logger->info('error msg:'. $e->getMessage() . ' trace:'. $e->getTraceAsString());
                //throw $e;
            }

            if(count($orders)<$this->rows_per_loop){
                break;
            }

            $i++;

        }

    }


}
